package com.nd.pagejump;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;

public class EUPageJump extends CordovaPlugin {
	final String TAG = "PageJump";
	public final static String JSON_RESULT = "JSON_RESULT";
	public final static String PARAMS_TITLE = "title";
	public final static String PARAMS_TARGET_PAGE = "targetPagePath";

	CallbackContext mCallbackContext;
	boolean mbResotreData = true;

	public static HashSet<String> mHashSet;
    private static Class mActivityClass = PageJumpAct.class;

    private static PageJumpProto mPageJumpProto;

	@Override
	public void initialize(CordovaInterface cordova, CordovaWebView webView) {
		super.initialize(cordova, webView);
		
		// 读取assets下的文件结构
//		String bb = Environment.getExternalStorageDirectory().getPath()
//				+ "/nd/tat/";
//		File file = new File(bb);
//		file.mkdirs();
//		mFileHashMap = CopyAssets(cordova.getActivity().getAssets(), "www", bb);
	}

    /**
     * 设置默认跳转到的activity
     * @param activity
     */
    public static void setActivity(Activity activity) {
        mActivityClass = activity.getClass();
    }

    /**
     * 设置页面跳转协议
     * @param pageJumpProto
     */
    public static void setPageJumpProto(PageJumpProto pageJumpProto) {
        mPageJumpProto = pageJumpProto;
    }
	
	public static HashSet<String> getAssetHashSet(Context context) {
		if (mHashSet == null) {
			mHashSet = pluginsHashMap(context.getAssets(),"www/plugins");
		}
		return mHashSet;
	}
	
	/**
	 * 获取assets文件加下所有插件
	 * @param as
	 * @param assetDir
	 * @return
	 */
	public static HashSet<String> pluginsHashMap(AssetManager as,String assetDir) {
		HashSet<String> hashMap = new HashSet<String>();
		String[] files;
		try {
			files = as.list(assetDir);
		} catch (IOException e1) {
			return hashMap;
		}
		for (int i = 0; i < files.length; i++) {

			String fileName = files[i];
			// we make sure file name not contains '.' to be a folder.
			//if (!fileName.contains(".")) {
				if (0 == assetDir.length()) {
					hashMap.addAll(pluginsHashMap(as, fileName));
				} else {
					hashMap.addAll(pluginsHashMap(as, assetDir + "/" + fileName));
				}
				//continue;
			//}
			hashMap.add(assetDir + "/" + fileName);
			Log.e("EUPageJump", "fdfd:"+assetDir + "/" + fileName);
		}
		return hashMap;
	}

	/**
	 * 赋值aseets下文件到指定目录
	 * @param as
	 * @param assetDir
	 * @param dir
	 * @return
	 */
	private HashMap<String, String> CopyAssets(AssetManager as,
			String assetDir, String dir) {
		HashMap<String, String> hashMap = new HashMap<String, String>();
		String[] files;
		try {
			files = as.list(assetDir);
		} catch (IOException e1) {
			return hashMap;
		}
		File mWorkingPath = new File(dir);
		// if this directory does not exists, make one.
		if (!mWorkingPath.exists()) {
			if (!mWorkingPath.mkdirs()) {
				// Log.e("--CopyAssets--", "cannot create directory.");
			}
		}
		for (int i = 0; i < files.length; i++) {

			String fileName = files[i];
			// we make sure file name not contains '.' to be a folder.
			if (!fileName.contains(".")) {
				if (0 == assetDir.length()) {
					hashMap.putAll(CopyAssets(as, fileName, dir + fileName
							+ "/"));
				} else {
					hashMap.putAll(CopyAssets(as, assetDir + "/" + fileName,
							dir + fileName + "/"));
				}
				continue;
			}
			 Log.e("EUPageJump", "xxxxxxx:"+assetDir + "/" + fileName);
			hashMap.put(fileName, assetDir + "/" + fileName);
		}
		return hashMap;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) throws JSONException {
		if (action.equals("pushPage") || action.equals("presentModelPage")) {
			mbResotreData = true;
			mCallbackContext = callbackContext;

            if (null != mPageJumpProto) {
                mPageJumpProto.jumpToPage(this.cordova.getActivity(), this.webView, args.toString());
            } else {
                startAct(args.toString());
            }

			return true;
		} else if (action.equals("popPage")
				|| action.equals("dismissModelPage")) {
            if (null != mPageJumpProto) {
                mPageJumpProto.pageBack(this.cordova.getActivity(), this.webView);
            } else {
                Intent intent = new Intent();
                intent.putExtra(JSON_RESULT, args.toString());
                this.cordova.getActivity().setResult(Activity.RESULT_OK, intent);
                this.cordova.setActivityResultCallback(this);
            }
			return true;
		} else if (action.equals("getFromData")) {
			if (mbResotreData) {
				JSONObject data = getData();
				if (data != null && !TextUtils.isEmpty(data.toString())) {
					callbackContext.success(getData());
				}

			}
			return true;
		}

		return super.execute(action, args, callbackContext);
	}

	@Override
	public Uri remapUri(Uri uri) {
		// 要调用这个，必须在config.xml里添加<param name="onload" value="true" />
		if (uri != null) {
			Log.e("EUPageJump", "remapUri:" + uri);

			String uriString = uri.toString();
			if (uriString.endsWith("mcfly.jpg")) {
				uri = Uri
						.parse("http://www.23code.com/wp-content/uploads/2014/12/device-2014-12-19-162550.jpg");
				return uri;
			} else {
				if (uriString.endsWith(".html")) {
					// 如果是html则不做处理
				} else {
					
					if (uriString.endsWith("cordova.js")) {
						uri = Uri.parse("file:///android_asset/www/cordova.js");
						Log.e("EUPageJump", "xxxxxxxxxxx:cordova.js in");
						return uri;
					} 
					else if (uriString.endsWith("cordova_plugins.js")) {
						uri = Uri.parse("file:///android_asset/www/cordova_plugins.js");
						return uri;
					} 
					else if (!TextUtils.isEmpty(uriString)) {
						String targetString = replaceToAsset(uriString);
						return Uri.parse(targetString);
					}

					// TODO: 只要处理cordova.ja cordova_plugin.js
//					 if (uriString.endsWith("EUHttpPlugin.js")) {
//						uri = Uri.parse("file:///android_asset/www/plugins/com.nd.euhttpplugin/www/EUHttpPlugin.js");
//						return uri;
//					} else if (uriString.endsWith("EUPageJumpConstants.js")) {
//						uri = Uri.parse("file:///android_asset/www/plugins/com.nd.pagejump/www/EUPageJumpConstants.js");
//						return uri;
//					} else if (uriString.endsWith("EUPageJump.js")) {
//						uri = Uri.parse("file:///android_asset/www/plugins/com.nd.pagejump/www/EUPageJump.js");
//						return uri;
//					}
				}
			}
		}
		return super.remapUri(uri);
	}
	
	public String replaceToAsset(String urlString) {
		if (TextUtils.isEmpty(urlString) ) {
			return "";
		}
		if (urlString.contains("/plugins/")) {
			String needString = urlString.substring(urlString.indexOf("/plugins/"));
			if (getAssetHashSet(cordova.getActivity()).contains("www"+needString)) {
				// 文件存在
				String tt =  "file:///android_asset/www"+needString;
				return tt;
			} else {
				// 文件不存在，得试图从sd卡里取找，如果找不到，则映射到一个空文件
				return urlString;
			} 
			
		} else {
			return urlString;
		}
	}

	public static final String PAGEJUMP_TARGET = "PAGEJUMP_TARGET";
	public static final int PAGEJUMP_RESULT = 100;

	public void startAct(String argJsonString) {
		Intent intent = new Intent();
		intent.putExtra(PAGEJUMP_TARGET, argJsonString);

		intent.setClass(this.cordova.getActivity(), mActivityClass);
		cordova.setActivityResultCallback(this);

		this.cordova.getActivity().startActivityForResult(intent, 100);
		
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("onStart", "1");
			jsonObject.put("data", "");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mCallbackContext.success(jsonObject);
	}

	public JSONObject getData() {
		if (cordova.getActivity() instanceof PageJumpAct) {
			JSONObject argString = ((PageJumpAct) cordova.getActivity())
					.getData();
			return argString;
		}

		return null;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);

		if (resultCode == Activity.RESULT_OK) {
			if (intent != null) {
				mbResotreData = false;
				String resultString = intent.getStringExtra(JSON_RESULT);
				if (TextUtils.isEmpty(resultString)) {
					return;
				}
				
				JSONObject jsonObject = new JSONObject();
				try {
					JSONArray jsonArray = new JSONArray(resultString);
					jsonObject.put("onStart", "0");
					jsonObject.put("data", jsonArray.getString(0));
					
					PluginResult pluginResult = new PluginResult(
							PluginResult.Status.OK, jsonObject);
					pluginResult.setKeepCallback(true);
					mCallbackContext.sendPluginResult(pluginResult);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void onResume(boolean multitasking) {
		super.onResume(multitasking);
	}
}
